package com.shop2cn.iapi.shenqisettlement.testcase;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.shop2cn.iapi.shenqisettlement.parameter.OnHpSettledReq;
import com.shop2cn.iapi.shenqisettlement.parameter.bean.AgentProductBean;
import com.shop2cn.iapi.shenqisettlement.service.OnHpSettledCall;
import com.shop2cn.iapi.sqoptrade.resp.Order;
import com.shop2cn.iapi.sqoptrade.resp.TradingServiceResp;
import com.ymatou.iapi.synctrade.service.TradingSyncService;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.tag.P1;
import com.ymttest.business.service.AccountCallServiceV2;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.business.service.SQPayGateWayCallService;
import com.ymttest.business.service.YMTTrading.TradingCallService;
import com.ymttest.business.service.shenqi.DGSQBuildProxyChainCallService;
import com.ymttest.business.service.shenqi.RefundService;
import com.ymttest.business.service.shenqi.ShenqiSettlementService;
import com.ymttest.business.service.shenqi.SqDistributorService;
import com.ymttest.business.service.shenqi.SqPartnerService;
import com.ymttest.business.service.shenqi.SqTradingCallService;
import com.ymttest.business.service.shenqi.bean.ShenqiUserSet;
import com.ymttest.database.model.shenqisettlement.DistributorSettlement;
import com.ymttest.database.model.shenqisettlement.DistributorSettlementDetail;
import com.ymttest.database.model.shenqisettlement.OrderSettlementDetail;
import com.ymttest.database.model.shenqisettlement.ProxyFissionSettlementDetail;
import com.ymttest.database.model.shenqisettlement.ShengpaySharingConverge;
import com.ymttest.database.model.shenqisettlement.ShengpaySharingConvergeDetail;
import com.ymttest.database.sharding.db.sharding.model.OrderDetailPo;
import com.ymttest.database.sharding.db.sharding.model.OrderPo;
import com.ymttest.database.sharding.db.sharding.model.PaymentPo;
import com.ymttest.database.sharding.db.sqlwapper.OrderShardingWapper;
import com.ymttest.database.sqlwapper.shenqisettlement.DistributorSettlementDetailWrapper;
import com.ymttest.database.sqlwapper.shenqisettlement.DistributorSettlementWrapper;
import com.ymttest.database.sqlwapper.shenqisettlement.MchFeeConfigWrapper;
import com.ymttest.database.sqlwapper.shenqisettlement.OrderSettlementDetailWrapper;
import com.ymttest.database.sqlwapper.shenqisettlement.ProxyFissionSettlementDetailWrapper;
import com.ymttest.database.sqlwapper.shenqisettlement.ShengpaySharingConvergeDetailWrapper;
import com.ymttest.database.sqlwapper.shenqisettlement.ShengpaySharingConvergeWrapper;
import com.ymttest.utils.DataUtil;

/*
 *  需要在shengpay_account_info中添加分账所绑定的商户记录
 *  order_settlement中的thirdparty_payment_order_no值修改为8877665541397569
 */
public class Ts_ShengpaySharingAmount {

	private static OnHpSettledReq hpSettledReq = null;
	private static OnHpSettledCall hpSettledCall = new OnHpSettledCall();

	private static OrderShardingWapper wapper = new OrderShardingWapper();
	private static ShengpaySharingConvergeWrapper shengpaySharingConvergeWrapper = new ShengpaySharingConvergeWrapper();
	private static ShengpaySharingConvergeDetailWrapper shengpaySharingConvergeDetailWrapper = new ShengpaySharingConvergeDetailWrapper();
	private static OrderSettlementDetailWrapper orderSettlementDetailWrapper = new OrderSettlementDetailWrapper();

	// 盛付通手续费率
	private static String shengPayRate = "0.001";

	private static long autotest_goodsOwnerId = ShenqiUserSet.autotest_goodsOwnerId;
	private static long proxyFissionGoodsOwnerId = ShenqiUserSet.proxyFissionGoodsOwnerId;

	@BeforeClass
	public static void setUp() {
		Logger.createResultFile("盛付通分账");

		/**
		 * 将未结算的结算单置为废弃,防止结算的时间过长
		 */
		// orderSettlementWrapper.updateStatus();
	}

	@Before
	public void caseUp() {
		String accountid1;
		try {
			accountid1 = AccountCallServiceV2.getAccountId(20238699);
			AccountCallServiceV2.resetAccount(accountid1, new BigDecimal(
					9000000), new BigDecimal(0));

			hpSettledReq = new OnHpSettledReq();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@AfterClass
	public static void tearDown() {
		Logger.generateResult("ShengpaySharingAmount");

		new MchFeeConfigWrapper().deleteAutotestData();
		wapper.activeDeadCommunicationsLink(wapper);
	}

	@After
	public void caseDown() {
		Logger.end();
	}

	private void onHpSettled(long paymentId, PaymentPo payment,
			String shengPayRate, int count) throws Exception {

		if (count < 6) {

			hpSettledReq.setTradingId(paymentId);
			hpSettledReq.setOrderAmount(payment.getRealPaidAmount());
			hpSettledReq.setSettleCurrency(payment.getSettleCurrency());
			hpSettledReq
					.setSettleAmount(payment.getRealForeignAmount() != null ? payment
							.getRealForeignAmount() : payment
							.getForeignAmount());

			if (shengPayRate != null) {

				hpSettledReq.setSettleFee(payment.getRealPaidAmount().multiply(
						new BigDecimal(shengPayRate)));
			}

			hpSettledCall.setData(hpSettledReq);
			hpSettledCall.callService();

			if (!"ok".equalsIgnoreCase(hpSettledCall.getReturnData())) {

				Thread.sleep(3000 + count * 2000);
				count++;
				this.onHpSettled(paymentId, payment, shengPayRate, count);
			}
		} else {

			throw new Exception();
		}
	}

	/**
	 * 
	 * @param orderId
	 * @param orderType
	 *            (1：代理裂变订单 2：分销员订单)
	 */
	public void verfydb(Long orderId, int orderType) {

		List<OrderSettlementDetail> orderSettlementDetailList = orderSettlementDetailWrapper
				.selectAllOrderByOrderId(orderId);
		OrderPo orderPo = wapper.selectOrderbyOrderId(orderId);

		long goodsOwnerId = orderPo.getGoodsOwnerId();
		long sellerId = orderPo.getSellerId();
		long paymentId = orderPo.getPaymentId();

		BigDecimal settlementAmount = BigDecimal.ZERO;
		BigDecimal refundSettlementAmount = BigDecimal.ZERO;
		BigDecimal convergeAmount = BigDecimal.ZERO;

		List<ShengpaySharingConverge> expectList = new ArrayList<>();

		List<Long> orderSettlementDetailIds = new ArrayList<>();

		HashMap<Long, List<Long>> proxyFissionSettlementDetailIdMap = new HashMap<>();
		HashMap<Long, List<Long>> distributorSettlementDetailIdMap = new HashMap<>();

		if (orderType == 1) {

			List<OrderSettlementDetail> proxyFissionOrderSettlementDetailList = orderSettlementDetailList
					.stream()
					.filter(detailPo -> detailPo.getSettlement_type() == 5)
					.collect(Collectors.toList());

			settlementAmount = proxyFissionOrderSettlementDetailList.stream()
					.map(detailPo -> detailPo.getSettlement_amount())
					.reduce(BigDecimal.ZERO, BigDecimal::add);

			List<OrderSettlementDetail> proxyFissionRefundOrderSettlementDetailList = orderSettlementDetailList
					.stream()
					.filter(detailPo -> detailPo.getSettlement_type() == 6)
					.collect(Collectors.toList());

			refundSettlementAmount = proxyFissionRefundOrderSettlementDetailList
					.stream().map(detailPo -> detailPo.getSettlement_amount())
					.reduce(BigDecimal.ZERO, BigDecimal::add);

			convergeAmount = settlementAmount.add(refundSettlementAmount);

			ShengpaySharingConverge orderSettlementDetailShengpaySharingConverge = new ShengpaySharingConverge();

			orderSettlementDetailShengpaySharingConverge.setOrder_id(orderId);
			orderSettlementDetailShengpaySharingConverge
					.setSharing_user_id(goodsOwnerId);
			orderSettlementDetailShengpaySharingConverge.setSharing_biz_type(2);
			orderSettlementDetailShengpaySharingConverge
					.setAmount(convergeAmount);
			orderSettlementDetailShengpaySharingConverge.setSeller_id(sellerId);
			orderSettlementDetailShengpaySharingConverge
					.setGoods_owner_id(goodsOwnerId);

			expectList.add(orderSettlementDetailShengpaySharingConverge);

			ProxyFissionSettlementDetailWrapper proxyFissionSettlementDetailWrapper = new ProxyFissionSettlementDetailWrapper();

			List<ProxyFissionSettlementDetail> proxyFissionSettlementDetailList = proxyFissionSettlementDetailWrapper
					.selectByOrderId(orderId);

			for (OrderSettlementDetail orderSettlementDetail : proxyFissionOrderSettlementDetailList) {

				Long fissionProxyId = orderSettlementDetail
						.getFission_proxy_id();

				List<Long> proxyFissionSettlementDetailIds = new ArrayList<>();

				List<ProxyFissionSettlementDetail> fissionProxyIdSettlementDetailList = proxyFissionSettlementDetailList
						.stream()
						.filter(detailPo -> detailPo.getProxy_id().longValue() == fissionProxyId
								.longValue()).collect(Collectors.toList());

				convergeAmount = fissionProxyIdSettlementDetailList.stream()
						.map(detailPo -> detailPo.getSettlement_amount())
						.reduce(BigDecimal.ZERO, BigDecimal::add);

				for (ProxyFissionSettlementDetail proxyFissionSettlementDetail : fissionProxyIdSettlementDetailList) {

					proxyFissionSettlementDetailIds
							.add(proxyFissionSettlementDetail.getId());
					
					Logger.verifyEquals(true, proxyFissionSettlementDetail
							.getShengpay_sharing_converge(),
							"验证distributor_settlement_detail表的Shengpay_sharing_converge");
				}

				ShengpaySharingConverge proxyFissionSettlementDetailShengpaySharingConverge = new ShengpaySharingConverge();

				proxyFissionSettlementDetailShengpaySharingConverge
						.setOrder_id(orderId);
				proxyFissionSettlementDetailShengpaySharingConverge
						.setSharing_user_id(fissionProxyId);
				proxyFissionSettlementDetailShengpaySharingConverge
						.setSharing_biz_type(4);
				proxyFissionSettlementDetailShengpaySharingConverge
						.setAmount(convergeAmount);
				proxyFissionSettlementDetailShengpaySharingConverge
						.setSeller_id(sellerId);
				proxyFissionSettlementDetailShengpaySharingConverge
						.setGoods_owner_id(goodsOwnerId);

				expectList
						.add(proxyFissionSettlementDetailShengpaySharingConverge);

				orderSettlementDetailIds.add(orderSettlementDetail.getId());
				
				proxyFissionSettlementDetailIdMap.put(fissionProxyId,
						proxyFissionSettlementDetailIds);
				
				Logger.verifyEquals(true,
						orderSettlementDetail.getShengpay_sharing_converge(),
						"验证order_settlement_detail表的Shengpay_sharing_converge");
			}

			for (OrderSettlementDetail orderSettlementDetail : proxyFissionRefundOrderSettlementDetailList) {
				orderSettlementDetailIds.add(orderSettlementDetail.getId());
				
				Logger.verifyEquals(true,
						orderSettlementDetail.getShengpay_sharing_converge(),
						"验证order_settlement_detail表的Shengpay_sharing_converge");
			}

		} else {

			List<OrderSettlementDetail> distributorOrderSettlementDetailList = orderSettlementDetailList
					.stream()
					.filter(detailPo -> detailPo.getSettlement_type() == 2 || detailPo.getSettlement_type() == 7)
					.collect(Collectors.toList());

			settlementAmount = distributorOrderSettlementDetailList.stream()
					.map(detailPo -> detailPo.getSettlement_amount())
					.reduce(BigDecimal.ZERO, BigDecimal::add);

			List<OrderSettlementDetail> distributorRefundOrderSettlementDetailList = orderSettlementDetailList
					.stream()
					.filter(detailPo -> detailPo.getSettlement_type() == 3 || detailPo.getSettlement_type() == 8)
					.collect(Collectors.toList());

			refundSettlementAmount = distributorRefundOrderSettlementDetailList
					.stream().map(detailPo -> detailPo.getSettlement_amount())
					.reduce(BigDecimal.ZERO, BigDecimal::add);

			convergeAmount = settlementAmount.add(refundSettlementAmount);

			ShengpaySharingConverge orderSettlementDetailShengpaySharingConverge = new ShengpaySharingConverge();

			orderSettlementDetailShengpaySharingConverge.setOrder_id(orderId);
			orderSettlementDetailShengpaySharingConverge
					.setSharing_user_id(sellerId);
			orderSettlementDetailShengpaySharingConverge.setSharing_biz_type(1);
			orderSettlementDetailShengpaySharingConverge
					.setAmount(convergeAmount);
			orderSettlementDetailShengpaySharingConverge.setSeller_id(sellerId);
			orderSettlementDetailShengpaySharingConverge
					.setGoods_owner_id(goodsOwnerId);

			expectList.add(orderSettlementDetailShengpaySharingConverge);

			for (OrderSettlementDetail orderSettlementDetail : distributorOrderSettlementDetailList) {

				orderSettlementDetailIds.add(orderSettlementDetail.getId());
				Logger.verifyEquals(true,
						orderSettlementDetail.getShengpay_sharing_converge(),
						"验证order_settlement_detail表的Shengpay_sharing_converge");
			}

			for (OrderSettlementDetail orderSettlementDetail : distributorRefundOrderSettlementDetailList) {
				orderSettlementDetailIds.add(orderSettlementDetail.getId());
				Logger.verifyEquals(true,
						orderSettlementDetail.getShengpay_sharing_converge(),
						"验证order_settlement_detail表的Shengpay_sharing_converge");
			}
			
			DistributorSettlementDetailWrapper distributorSettlementDetailWrapper = new DistributorSettlementDetailWrapper();
			DistributorSettlementWrapper distributorSettlementWrapper = new DistributorSettlementWrapper();
			
			DistributorSettlement distributorSettlement = distributorSettlementWrapper.selectByPaymentIdAndOrderId(paymentId, orderId);
			
			Logger.verifyEquals(true,
					distributorSettlement.getShengpay_sharing_converge(),
					"验证distributor_settlement表的Shengpay_sharing_converge");

			List<DistributorSettlementDetail> distributorSettlementDetailList = distributorSettlementDetailWrapper
					.selectByOrderId(orderId);
			
			Map<Long, List<DistributorSettlementDetail>> distributorSettlementDetailMap = distributorSettlementDetailList
					.stream()
					.collect(
							Collectors
									.groupingBy(DistributorSettlementDetail::getDistributor_id));
			
			for (Map.Entry<Long, List<DistributorSettlementDetail>> entry : distributorSettlementDetailMap.entrySet()) {
				
				List<Long> distributorSettlementDetailIds = new ArrayList<>();
				
				Long distributorId = entry.getKey();
				
				List<DistributorSettlementDetail> distributorIdSettlementDetailList = distributorSettlementDetailMap
						.get(distributorId).stream()
						.collect(Collectors.toList());
				
				convergeAmount = distributorIdSettlementDetailList.stream()
						.map(detailPo -> detailPo.getSettlement_amount())
						.reduce(BigDecimal.ZERO, BigDecimal::add);

				for (DistributorSettlementDetail distributorSettlementDetail : distributorIdSettlementDetailList) {

					distributorSettlementDetailIds
							.add(distributorSettlementDetail.getId());
					
					Logger.verifyEquals(true,
							distributorSettlementDetail.getShengpay_sharing_converge(),
							"验证distributor_settlement_detail表的Shengpay_sharing_converge");
				}

				ShengpaySharingConverge distributorSettlementDetailShengpaySharingConverge = new ShengpaySharingConverge();

				distributorSettlementDetailShengpaySharingConverge
						.setOrder_id(orderId);
				distributorSettlementDetailShengpaySharingConverge
						.setSharing_user_id(distributorId);
				distributorSettlementDetailShengpaySharingConverge
						.setSharing_biz_type(3);
				distributorSettlementDetailShengpaySharingConverge
						.setAmount(convergeAmount);
				distributorSettlementDetailShengpaySharingConverge
						.setSeller_id(sellerId);
				distributorSettlementDetailShengpaySharingConverge
						.setGoods_owner_id(goodsOwnerId);

				expectList
						.add(distributorSettlementDetailShengpaySharingConverge);
				
				distributorSettlementDetailIdMap.put(distributorId,
						distributorSettlementDetailIds);
			}
		}

		List<ShengpaySharingConverge> actualList = shengpaySharingConvergeWrapper
				.selectByOrderId(orderId);
		
		actualList = actualList
				.stream()
				.sorted(Comparator
						.comparing(ShengpaySharingConverge::getSharing_user_id))
				.collect(Collectors.toList());
		expectList = expectList
				.stream()
				.sorted(Comparator
						.comparing(ShengpaySharingConverge::getSharing_user_id))
				.collect(Collectors.toList());

		Logger.verifyEquals(expectList.size(), actualList.size(),
				"验证shengpay_sharing_converge列表大小");

		for (int i = 0; i < expectList.size(); i++) {

			ShengpaySharingConverge expectResult = expectList.get(i);
			ShengpaySharingConverge actualResult = actualList.get(i);

			Logger.comment("校验shengpay_sharing_converge详细数据");

			Logger.verifyEquals(expectResult.getOrder_id(),
					actualResult.getOrder_id(), "验证Order_id");
			Logger.verifyEquals(expectResult.getSharing_user_id(),
					actualResult.getSharing_user_id(), "验证Sharing_user_id");
			DataUtil.verifyDecimalEquals(expectResult.getAmount(),
					actualResult.getAmount(), "验证Amount");
			Logger.verifyEquals(expectResult.getSharing_biz_type(),
					actualResult.getSharing_biz_type(), "验证Sharing_biz_type");
			Logger.verifyEquals(expectResult.getSeller_id(),
					actualResult.getSeller_id(), "验证Seller_id");
			Logger.verifyEquals(expectResult.getGoods_owner_id(),
					actualResult.getGoods_owner_id(), "验证Order_id");
			
			List<ShengpaySharingConvergeDetail> shengpaySharingConvergeDetailList = shengpaySharingConvergeDetailWrapper
					.selectByConvergeId(actualResult.getId());

			if (actualResult.getSharing_biz_type() == 2
					|| actualResult.getSharing_biz_type() == 1) {

				shengpaySharingConvergeDetailList = shengpaySharingConvergeDetailList
						.stream()
						.sorted(Comparator
								.comparing(ShengpaySharingConvergeDetail::getSettlement_detail_id))
						.collect(Collectors.toList());

				orderSettlementDetailIds = orderSettlementDetailIds.stream()
						.sorted().collect(Collectors.toList());

				Logger.verifyEquals(orderSettlementDetailIds.size(),
						shengpaySharingConvergeDetailList.size(),
						"验证shengpay_sharing_converge_detail结算表类型为order_settlement_detail的列表大小");

				for (int j = 0; j < shengpaySharingConvergeDetailList.size(); j++) {

					ShengpaySharingConvergeDetail actualShengpaySharingConvergeDetail = shengpaySharingConvergeDetailList
							.get(j);

					Logger.comment("校验shengpay_sharing_converge_detail结算表类型为order_settlement_detail的详细数据");

					Logger.verifyEquals(1, actualShengpaySharingConvergeDetail
							.getSettlement_source_type(),
							"验证Settlement_source_type");
					Logger.verifyEquals(orderSettlementDetailIds.get(j),
							actualShengpaySharingConvergeDetail
									.getSettlement_detail_id(),
							"验证Settlement_detail_id");
				}
			} else if (actualResult.getSharing_biz_type() == 4) {

				List<Long> proxyFissionSettlementDetailIds = proxyFissionSettlementDetailIdMap
						.get(actualResult.getSharing_user_id());

				Logger.verifyEquals(proxyFissionSettlementDetailIds.size(),
						shengpaySharingConvergeDetailList.size(),
						"验证shengpay_sharing_converge_detail结算表类型为proxy_fission_settlement_detail的列表大小");

				for (int j = 0; j < shengpaySharingConvergeDetailList.size(); j++) {

					ShengpaySharingConvergeDetail actualShengpaySharingConvergeDetail = shengpaySharingConvergeDetailList
							.get(j);

					Logger.comment("校验shengpay_sharing_converge_detail结算表类型为proxy_fission_settlement_detail的详细数据");

					Logger.verifyEquals(3, actualShengpaySharingConvergeDetail
							.getSettlement_source_type(),
							"验证Settlement_source_type");
					Logger.verifyEquals(proxyFissionSettlementDetailIds.get(j),
							actualShengpaySharingConvergeDetail
									.getSettlement_detail_id(),
							"验证Settlement_detail_id");
				}
			} else {
				
				List<Long> distributorSettlementDetailIds = distributorSettlementDetailIdMap
						.get(actualResult.getSharing_user_id());
				
				Logger.verifyEquals(distributorSettlementDetailIds.size(),
						shengpaySharingConvergeDetailList.size(),
						"验证shengpay_sharing_converge_detail结算表类型为distributor_settlement_detail的列表大小");
				
				for (int j = 0; j < shengpaySharingConvergeDetailList.size(); j++) {

					ShengpaySharingConvergeDetail actualShengpaySharingConvergeDetail = shengpaySharingConvergeDetailList
							.get(j);

					Logger.comment("校验shengpay_sharing_converge_detail结算表类型为distributor_settlement_detail的详细数据");

					Logger.verifyEquals(2, actualShengpaySharingConvergeDetail
							.getSettlement_source_type(),
							"验证Settlement_source_type");
					Logger.verifyEquals(distributorSettlementDetailIds.get(j),
							actualShengpaySharingConvergeDetail
									.getSettlement_detail_id(),
							"验证Settlement_detail_id");
				}
			 }	
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ShengpaySharingAmount_001() {
		Logger.start(true, "代购神器，代理裂变（货头-店主），2个邀请人，多商品，带优惠，盛付通支付，已发货，已结算");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createPromotersProxychain((int) proxyFissionGoodsOwnerId,
							2, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrderWithAllPromotion(productBean, BigDecimal.ZERO,
							proxyFissionGoodsOwnerId);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId(), "wxsqBuyer", "6010");

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString(), 6010);

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(5000);

			Logger.comment("前置数据准备结束");

			long paymentId = wapper.selectOrderbyOrderId(orderId)
					.getPaymentId();

			PaymentPo payment = wapper.selectPaymentById(paymentId);

			this.onHpSettled(paymentId, payment, shengPayRate, 1);

			// 接单
			SqTradingCallService.sellerAcceptOrder(
					proxyFissionGoodsOwnerId, orderId);

			TradingSyncService.getSyncResult(orderId);

			// 发货
			SqTradingCallService.delivery(proxyFissionGoodsOwnerId,
					orderId, 1234L, null);

			// 代购神器结算
			ShenqiSettlementService.doSettlement();
			Thread.sleep(3000);

			// 代理裂变结算
			ShenqiSettlementService.executeProxyFissionSettlementTask();
			Thread.sleep(3000);

			ShenqiSettlementService
					.executeShengPayMerchantSharingConvergeTask();

			Logger.comment(String.format("orderId: %s; paymentId: %s", orderId,
					paymentId));

			this.verfydb(orderId, 1);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ShengpaySharingAmount_002() {
		Logger.start(true, "代购神器，代理商，代理裂变（货头-店主），1个邀请人，未调价，已接单，已结算, 发起全部退货退款");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createPromotersProxychain((int) proxyFissionGoodsOwnerId,
							1, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrderWithAllPromotion(productBean, BigDecimal.ZERO,
							proxyFissionGoodsOwnerId);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId(), "wxsqBuyer", "6010");

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString(), 6010);

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			long paymentId = wapper.selectOrderbyOrderId(orderId)
					.getPaymentId();

			PaymentPo payment = wapper.selectPaymentById(paymentId);

			this.onHpSettled(paymentId, payment, null, 1);

			// 接单
			SqTradingCallService.sellerAcceptOrder(
					proxyFissionGoodsOwnerId, orderId);
			TradingSyncService.getSyncResult(orderId);

			SqTradingCallService.delivery(proxyFissionGoodsOwnerId,
					orderId, 1234L, null);

			// 代购神器结算
			ShenqiSettlementService.doSettlement();
			Thread.sleep(3000);

			// 退货退款
			RefundService.createFullRefundSuccess(orderId,
					proxyFissionGoodsOwnerId, paymentId, userId);
			Thread.sleep(5000);

			// 代理裂变结算
			ShenqiSettlementService.executeProxyFissionSettlementTask();
			Thread.sleep(3000);

			ShenqiSettlementService
					.executeShengPayMerchantSharingConvergeTask();

			Logger.comment(String.format("orderId: %s; paymentId: %s", orderId,
					paymentId));

			this.verfydb(orderId, 1);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ShengpaySharingAmount_003() {
		Logger.start(true,
				"代购神器，代理商，代理裂变（货头-店主），2个邀请人，代理订单，未调价，已接单，已结算, 发起部分退货退款");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createPromotersProxychain((int) proxyFissionGoodsOwnerId,
							2, false);

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrderWithAllPromotion(productBean, BigDecimal.ZERO,
							proxyFissionGoodsOwnerId);

			Long userId = placeOrderResp.getUserId();
			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();
			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId(), "wxsqBuyer", "6010");

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString(), 6010);

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(10000);

			Logger.comment("前置数据准备结束");

			long paymentId = wapper.selectOrderbyOrderId(orderId)
					.getPaymentId();

			PaymentPo payment = wapper.selectPaymentById(paymentId);

			this.onHpSettled(paymentId, payment, null, 1);

			// 接单
			SqTradingCallService.sellerAcceptOrder(
					proxyFissionGoodsOwnerId, orderId);
			TradingSyncService.getSyncResult(orderId);

			SqTradingCallService.delivery(proxyFissionGoodsOwnerId,
					orderId, 1234L, null);

			// 代购神器结算
			ShenqiSettlementService.doSettlement();
			Thread.sleep(3000);

			// 退货退款
			OrderDetailPo orderDetailPo = placeOrderResp.getOrderList().get(0)
					.getOrderDetailPoList().get(0);

			RefundService.createOnePartProductRefundSuccess(orderId,
					orderDetailPo, proxyFissionGoodsOwnerId, paymentId, userId,
					1);

			Thread.sleep(5000);

			// 代理裂变结算
			ShenqiSettlementService.executeProxyFissionSettlementTask();
			Thread.sleep(3000);

			ShenqiSettlementService
					.executeShengPayMerchantSharingConvergeTask();

			Logger.comment(String.format("orderId: %s; paymentId: %s", orderId,
					paymentId));

			this.verfydb(orderId, 1);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ShengpaySharingAmount_004() {
		Logger.start(true, "代购神器，分销员体系+合伙人体系"
				+ "商户-》一级分销员1-》一级分销员2（合伙人），已结算，验证分销数据");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 1, false,
							false);

			long merchantId = productBean.getSellerId();
			Long userId = (long) new OrderCallService().createNewUser();

			List<Long> distributorList = SqDistributorService
					.buildSqDistributorRelation(productBean.getSellerId(), 0,
							4, 0);
			SqDistributorService.setDistributorConfig(merchantId, 2, false);
			SqDistributorService.bindDistributorConsumerRelation(userId,
					merchantId, distributorList.get(2));

			// 设置合伙人配置
			SqPartnerService.savePartnerConfig(merchantId);

			// 将分销员设置成合伙人
			SqPartnerService.enablePartner(merchantId, distributorList.get(2));

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrderWithUserIdAndSaleman(productBean, userId, null);

			long orderId = placeOrderResp.getOrderList().get(0).getOrderId();

			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId(), "wxsqBuyer", "6010");

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString(),
					productBean.getCurrency(), 6010);

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(5000);

			long paymentId = wapper.selectOrderbyOrderId(orderId)
					.getPaymentId();

			PaymentPo payment = wapper.selectPaymentById(paymentId);

			this.onHpSettled(paymentId, payment, null, 1);

			// 接单
			TradingCallService
					.sellerAcceptOrder(autotest_goodsOwnerId, orderId);
			TradingSyncService.getSyncResult(orderId);

			// 发货
			SqTradingCallService.delivery(autotest_goodsOwnerId, orderId,
					null, null);
			TradingSyncService.getSyncResult(orderId);

			// 商户分账申请
			ShenqiSettlementService
					.executeShengPayMerchantSharingConvergeTask();

			// 修改分账状态为1


			// 商户结算
			ShenqiSettlementService.doSettlement();
			Thread.sleep(3000);

			// 分销员分账申请
			ShenqiSettlementService
					.executeShengPayMerchantSharingConvergeTask();

			// 修改分账状态为1

			// 代购神器分销订单结算
			SqDistributorService.doDistributorSettlement();
			Thread.sleep(3000);

			Logger.comment("前置数据准备结束");

			Logger.comment(String.format("orderId: %s; paymentId: %s", orderId,
					paymentId));
			
			this.verfydb(orderId, 2);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	@Test
	@Category(P1.class)
	@TestCase
	public void Tc_ShengpaySharingAmount_005() {
		Logger.start(
				true,
				"代购神器，分销员体系+合伙人"
						+ "商户-》一级分销员1-》一级分销员2（合伙人）-》一级分销员3（合伙人），盛付通支付，已结算，部分退货退款，验证分销数据");
		try {
			// 创建订单
			Logger.comment("前置数据准备");

			AgentProductBean productBean = DGSQBuildProxyChainCallService
					.createProxychain((int) autotest_goodsOwnerId, 1, false,
							false);

			long merchantId = productBean.getSellerId();
			Long userId = (long) new OrderCallService().createNewUser();

			List<Long> distributorList = SqDistributorService
					.buildSqDistributorRelation(productBean.getSellerId(), 0,
							4, 0);
			SqDistributorService.setDistributorConfig(merchantId, 3, false);
			SqDistributorService.bindDistributorConsumerRelation(userId,
					merchantId, distributorList.get(3));

			// 设置合伙人配置
			SqPartnerService.savePartnerConfig(merchantId);

			// 将分销员设置成合伙人
			SqPartnerService.enablePartner(merchantId, distributorList.get(2));
			SqPartnerService.enablePartner(merchantId, distributorList.get(3));

			TradingServiceResp placeOrderResp = SqTradingCallService
					.placeOrderWithUserIdAndSaleman(productBean, userId, null);

			Order order = placeOrderResp.getOrderList().get(0);

			long orderId = order.getOrderId();

			BigDecimal totalPrice = placeOrderResp.getPayableAmount();

			// 支付订单
			Long thirdTradingId = SqTradingCallService.payOrder(userId,
					placeOrderResp.getTradingId(), "wxsqBuyer", "6010");

			// 支付网关支付回调交易
			SQPayGateWayCallService.DGSQNotifyCall(
					String.valueOf(thirdTradingId),
					totalPrice.subtract(BigDecimal.ZERO).toString(),
					userId.intValue(), BigDecimal.ZERO.toPlainString(),
					productBean.getCurrency(), 6010);

			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(5000);

			long paymentId = wapper.selectOrderbyOrderId(orderId)
					.getPaymentId();

			PaymentPo payment = wapper.selectPaymentById(paymentId);

			this.onHpSettled(paymentId, payment, shengPayRate, 1);

			// 接单
			TradingCallService
					.sellerAcceptOrder(autotest_goodsOwnerId, orderId);
			TradingSyncService.getSyncResult(orderId);
			Thread.sleep(3000);

			// 退货退款
			// 第一个订单下的商品列表
			List<OrderDetailPo> orderDetailPoList = order
					.getOrderDetailPoList();

			int productCount = 2;

			RefundService.createOnePartProductRefundSuccess(orderId,
					orderDetailPoList.get(0), autotest_goodsOwnerId, paymentId,
					userId, productCount);

			// 发货
			SqTradingCallService.delivery(autotest_goodsOwnerId, orderId,
					null, null);
			TradingSyncService.getSyncResult(orderId);

			ShenqiSettlementService.doSettlement();
			Thread.sleep(3000);

			// 代购神器分销订单结算
			SqDistributorService.doDistributorSettlement();
			Thread.sleep(3000);

			Logger.comment("前置数据准备结束");

			ShenqiSettlementService
					.executeShengPayMerchantSharingConvergeTask();

			Logger.comment(String.format("orderId: %s; paymentId: %s", orderId,
					paymentId));
			
			this.verfydb(orderId, 2);

		} catch (Exception e) {
			Logger.fail(e);
		}
	}

	public static void main(String[] args) {

		Ts_ShengpaySharingAmount test = new Ts_ShengpaySharingAmount();

		test.verfydb(1520016136L, 2);
	}
}
